package com.konne.nightmare.FastPublicOpinion.ui.information.activity;

import android.app.DownloadManager;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.gyf.immersionbar.ImmersionBar;
import com.konne.nightmare.FastPublicOpinion.R;
import com.konne.nightmare.FastPublicOpinion.utils.Utility;
import com.konne.nightmare.FastPublicOpinion.utils.Utils;
import com.konne.nightmare.FastPublicOpinion.utils.X5WebView;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.TbsReaderView;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class    X5WebViewActivity extends AppCompatActivity {

    /*    @BindView(R.id.tv_title)
        TextView tv_title;*/
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.x5WebView)
    X5WebView x5WebView;
    @BindView(R.id.ll_x5webView)
    LinearLayout llX5webView;
    @BindView(R.id.tv_head_name)
    TextView tv_head_name;

    private Button mDownloadBtn;

    private String mUrl;
    private String mTitle;
    private DownloadManager mDownloadManager;
    private long mRequestId;
    private DownloadObserver mDownloadObserver;
    private String mFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.white).fullScreen(true)
                .statusBarDarkFont(true)
                .init();
        setContentView(R.layout.activity_x5webview);
        ButterKnife.bind(this);
        initViews();

//        initIntent();
    }

    private void initViews() {
        setWebViewListener();
    }

    private void initIntent() {

        mUrl = getIntent().getStringExtra(Utils.INTENT_URL);
        mTitle = getIntent().getStringExtra(Utils.INTENT_TITLE);
        tv_head_name.setText(mTitle);
        if (Utility.isEmpty(mUrl)) {
            return;
        }

        if (mUrl.endsWith(".png")
                || mUrl.endsWith(".jpg")
                || mUrl.endsWith(".jpeg")
                || mUrl.endsWith(".webp")
        ) {
            ImageView ivImg = new ImageView(this);
            ivImg.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            ivImg.setLayoutParams(lp);
            llX5webView.removeAllViews();
            llX5webView.addView(ivImg);
            //加载图片链接 替换即可
//            ImageLoader.getInstance().loadImage(ivImg, mUrl);
            return;
        }


        if (mUrl.endsWith(".doc")
                || mUrl.endsWith(".docx")
                || mUrl.endsWith(".xls")
                || mUrl.endsWith(".xlsx")
                || mUrl.endsWith(".ppt")
                || mUrl.endsWith(".pptx")
                || mUrl.contains(".pdf")
        ) {
            mDownloadBtn = new Button(this);
            ViewGroup.LayoutParams lp1 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mDownloadBtn.setLayoutParams(lp1);
            TbsReaderView tbsReaderView = new TbsReaderView(this, (TbsReaderView.ReaderCallback) this);
            ViewGroup.LayoutParams lp2 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            tbsReaderView.setLayoutParams(lp2);
            llX5webView.removeAllViews();
            llX5webView.addView(mDownloadBtn);
            llX5webView.addView(tbsReaderView);

            mFileName = parseName(mUrl);

            if (isLocalExist()) {
                mDownloadBtn.setVisibility(View.GONE);
                displayFile();
            } else {
                startDownload();
            }
        } else {
            x5WebView.loadUrl(mUrl);
        }
    }

    private void setWebViewListener() {
        //加载的url按规定的使用即可
        com.tencent.smtt.sdk.WebSettings settings = x5WebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setSupportMultipleWindows(true);
        settings.setAllowContentAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setSavePassword(false);
        settings.setSaveFormData(false);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setTextZoom(100);
        // 添加js交互接口类，并起别名 imagelistner
//        x5WebView.addJavascriptInterface(new JavascriptInterface(this), "Android");
//        x5WebView.setWebViewClient(new MyWebViewClient());

        x5WebView.setWebChromeClient(new WebChromeClient() {
            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (mTitle == null || TextUtils.isEmpty(mTitle) || mTitle.equals("")) {
                    mTitle = title;
                }

                /*                tv_title.setText(mTitle);*/
            }

            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    mProgressBar.setVisibility(View.VISIBLE);
                } else if (newProgress == 100) {
                    mProgressBar.setVisibility(View.GONE);
                }
                mProgressBar.setProgress(newProgress);
            }
        });

        x5WebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                Log.e("url=", url);
                // TODO: 2017-5-6 处理下载事件
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });

        x5WebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                Log.e("url=", url);
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    if (url.contains(".apk")) {
                        Uri uri = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                        return true;
                    }
                    return false;
                } else {
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
//                        Toast.makeText(X5WebViewActivity.this, "未安装相应的应用", Toast.LENGTH_LONG).show();
                    }
                    return true;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                view.getSettings().setJavaScriptEnabled(true);
                // html加载完成之后，添加监听图片的点击js函数
                x5WebView.loadUrl("javascript:window.Android.openImage(document.head.innerHTML);");
                super.onPageFinished(view, url);
            }
        });
        initIntent();
    }


    @OnClick({R.id.iv_back})
    public void onClick(View view) {
        if (view.getId() == R.id.iv_back) {
            onBackPressed();
        }
    }

    //点击返回上一页面而不是退出浏览器
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && x5WebView.canGoBack()) {
            x5WebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (null != x5WebView && x5WebView.canGoBack()) {
            x5WebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (x5WebView != null) {
            x5WebView.destroy();
        }
    }

    private void displayFile() {
//        Bundle bundle = new Bundle();
//        bundle.putString("filePath", "/storage/emulated/0/uu/HTTP权威指南.pdf");
//        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
//        boolean result = mTbsReaderView.preOpen(parseFormat("HTTP权威指南.pdf"), false);
//        if (result) {
//            mTbsReaderView.openFile(bundle);
//        }
    }


    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    private String parseName(String url) {
        String fileName = null;
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        return fileName;
    }

    private boolean isLocalExist() {
        return getLocalFile().exists();
    }

    private File getLocalFile() {
        return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), mFileName);
    }


    private void startDownload() {
        mDownloadObserver = new DownloadObserver(new Handler());
        getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, mDownloadObserver);

        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mUrl));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mFileName);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        mRequestId = mDownloadManager.enqueue(request);
    }

    private class DownloadObserver extends ContentObserver {

        private DownloadObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            Log.i("downloadUpdate: ", "onChange(boolean selfChange, Uri uri)");
            queryDownloadStatus();
        }
    }

    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(mRequestId);
        Cursor cursor = null;
        try {
            cursor = mDownloadManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                //已经下载的字节数
                int currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //总需下载的字节数
                int totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //状态所在的列索引
                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                Log.i("downloadUpdate: ", currentBytes + " " + totalBytes + " " + status);
                mDownloadBtn.setText("正在下载：" + currentBytes + "/" + totalBytes);
                if (DownloadManager.STATUS_SUCCESSFUL == status && mDownloadBtn.getVisibility() == View.VISIBLE) {
                    mDownloadBtn.setVisibility(View.GONE);
                    mDownloadBtn.performClick();
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


}
